package com.yb.framework.core.utils; 

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;

import javax.xml.bind.DatatypeConverter;

public class MD5Util {
	
	private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
	
	/**
	 * 转换字节数组为16进制字串
	 */
	private static String byteArrayToHexString(byte[] b) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			resultSb.append(byteToHexString(b[i]));
		}
		return resultSb.toString();
	}
	
	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0) n = 256 + n;
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}
	
	public static String encode(String origin) {
		String resultString = null;
		try {
			resultString = new String(origin);
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
		} catch (Exception ex) {

		}
		return resultString;
	}
	
	public static String encodeFile(File file) throws Exception{  
    	MessageDigest mMessageDigest = MessageDigest.getInstance("MD5");  
        InputStream fis = new FileInputStream(file);  
        byte[] buffer = new byte[1024];  
        int length = -1;  
        while ((length = fis.read(buffer, 0, 1024)) > 0) {  
            mMessageDigest.update(buffer, 0, length);  
        }  
        fis.close();  
        return new BigInteger(1, mMessageDigest.digest()).toString(16);  
	}
	
	private static boolean isSmaeFile(File file1, File file2) throws Exception{
	    boolean result = true;  
	    if (file1.length() != file2.length()) {  
	        result = false;  
	    } else {  
	        String file1MD5 = MD5Util.encodeFile(file1);  
	        String file2MD5 = MD5Util.encodeFile(file2);  
	        if (file1MD5 != null && !file1MD5.equals(file2MD5)) {  
	            result = false;  
	        } 
	    }
	    return result;  
	}  
	
	public static String getMD5Hash(String data) {
		String result = null;
		try {
			MessageDigest digest = MessageDigest.getInstance("MD5");
			byte[] hash = digest.digest(data.getBytes("UTF-8"));
			return bytesToHex(hash);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}
	
	private static String bytesToHex(byte[] hash) {
		return DatatypeConverter.printHexBinary(hash);
	}
	
	public static void main(String[] args) throws Exception{
		File file1 = new File("F:\\ProductService-3.5.jar");
		File file2 = new File("E:\\1235.txt");
		System.out.println(isSmaeFile(file1,file2));
		System.out.println(encodeFile(file1));
		System.out.println(encodeFile(file2));;
	}
}